package opn.srn.executor;

import java.io.File;
import java.util.Collection;

import opn.srn.command.CommandHelper;
import opn.srn.command.ICommand;
import opn.srn.plugin.PluginManager;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;

public class CommandExecutor {

	String commandFileName;

	public CommandExecutor(String commandFileName) {
		this.commandFileName = commandFileName;
	}

	void execute() throws Exception {
		ICommand<?> command = CommandHelper.load(commandFileName);
		command.execute();
	}

	private static Options cmdLineArgumentOptions() {
		Options options = new Options();

		options.addOption(new Option("command", true, "Command file"));

		return options;
	}

	public static void main(String[] args) throws Exception {
		if (System.getenv("plugindir") == null) {
			System.out.println("plugindir not set in environment...");
			return;
		}

		String pluginDir = System.getenv("plugindir");
		if (pluginDir.isEmpty()) {
			System.out.println("plugindir not set in environment...");
			return;
		}

		CommandLineParser parser = new GnuParser();
		CommandLine cmdArgs = parser.parse(cmdLineArgumentOptions(), args, true);
		if (cmdArgs.hasOption("command") == false) {
			System.out.println("command option not set...");
			return;
		}

		String commandFileName = cmdArgs.getOptionValue("command");
		if (commandFileName == null || commandFileName.isEmpty()) {
			System.out.println("command option not set...");
			return;
		}

		PluginManager pluginManager = new PluginManager();
		try {
			pluginManager.startPlugins(getAllPluginConfigFileNames(pluginDir));
			CommandExecutor executor = new CommandExecutor(commandFileName);
			executor.execute();
		} finally {
			pluginManager.stopPlugins();
		}

	}

	private static Collection<File> getAllPluginConfigFileNames(String pluginDir) {
		return FileUtils.listFiles(new File(pluginDir), FileFilterUtils.nameFileFilter("plugin.ini"),
				FileFilterUtils.trueFileFilter());
	}

}
